package com.platform.controller;

import com.platform.entity.CouponEntity;
import com.platform.entity.CouponGoodsEntity;
import com.platform.entity.GoodsEntity;
import com.platform.service.CouponGoodsService;
import com.platform.service.CouponService;
import com.platform.service.GoodsService;
import com.platform.service.UserCouponService;
import com.platform.utils.PageUtils;
import com.platform.utils.Query;
import com.platform.utils.R;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 优惠券Controller
 *
 * @author lipengjun
 * @email 939961241@qq.com
 * @date 2017-08-19 12:53:26
 */
@RestController
@RequestMapping("coupon")
public class CouponController {

    @Autowired
    private CouponService couponService;
    @Autowired
    private CouponGoodsService couponGoodsService;
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private UserCouponService userCouponService;

    /**
     * 查看列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("coupon:list")
    public R list(@RequestParam Map<String, Object> params) {
        //查询列表数据
        Query query = new Query(params);

        List<CouponEntity> couponList = couponService.queryList(query);
        int total = couponService.queryTotal(query);

        PageUtils pageUtil = new PageUtils(couponList, total, query.getLimit(), query.getPage());

        return R.ok().put("page", pageUtil);
    }


    /**
     * 查看信息
     */
    @RequestMapping("/info/{id}")
    @RequiresPermissions("coupon:info")
    public R info(@PathVariable("id") Integer id) {
        CouponEntity coupon = couponService.queryObject(id);

        Map<String, Object> params = new HashMap<>();
        params.put("isDelete", 0);
        params.put("couponId", id);
        List<Integer> list = goodsService.queryListByCoupon(params);
        coupon.setGoods(list);

        return R.ok().put("coupon", coupon);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    @RequiresPermissions("coupon:save")
    @Transactional(rollbackFor = Exception.class)
    public R save(@RequestBody CouponEntity coupon) {

        couponService.save(coupon);
        List<Integer> goods = coupon.getGoods();


        //todo 判断"按照商品发放"的情况
        if (coupon.getSendType() == 3 && coupon.getIsAllApplicable() == 0 && goods.size() == 0) {
            return R.error("请选择商品");
        }
        //todo 判断"新用户注册"和"包邮优惠" 4-新用户注册;7-包邮优惠
        if (coupon.getSendType() == 4 || coupon.getSendType() == 7) {
            Map<String, Object> params = new HashMap<>();
            params.put("sendType", 4);
            List<CouponEntity> couponEntities = couponService.queryList(params);
            if (couponEntities.size() > 0) {
                return R.error("已存在新用户注册的优惠券");
            }
            params.put("sendType", 7);
            couponEntities = couponService.queryList(params);
            if (couponEntities.size() > 0) {
                return R.error("已存在包邮的优惠券");
            }
        }

        //todo 保存
        if (goods != null && goods.size() > 0) {
            addCouponGoods(goods, coupon.getId());
        }
        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @RequiresPermissions("coupon:update")
    @Transactional(rollbackFor = Exception.class)
    public R update(@RequestBody CouponEntity coupon) {
        List<Integer> goods = coupon.getGoods();

        //todo 判断 按照商品发放
        if (coupon.getSendType() == 3 && goods.size() == 0) {
            return R.error("请选择商品");
        }

        couponService.update(coupon);

        //todo 清空绑定的商品
        Map<String, Object> params = new HashMap<>();
        params.put("couponId", coupon.getId());
        List<CouponGoodsEntity> couponGoodsEntities = couponGoodsService.queryList(params);
        if (couponGoodsEntities.size() > 0) {
            for (CouponGoodsEntity item : couponGoodsEntities) {
                couponGoodsService.delete(item.getId());
            }
        }
        //todo 重新保存
        if (goods != null && goods.size() > 0) {
            addCouponGoods(goods, coupon.getId());
        }
        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("coupon:delete")
    @Transactional(rollbackFor = Exception.class)
    public R delete(@RequestBody Integer[] ids) {
        //先进行关联删除
        userCouponService.deleteByCouponId(Arrays.asList(ids));
        couponService.deleteBatch(ids);
        return R.ok();
    }

    /**
     * 查看所有列表
     */
    @RequestMapping("/queryAll")
    public R queryAll(@RequestParam Map<String, Object> params) {
        List<CouponEntity> list = couponService.queryList(params);
        return R.ok().put("list", list);
    }

    /**
     * 按用户、商品下发优惠券
     *
     * @param params
     * @return
     */
    @RequiresPermissions("coupon:publish")
    @RequestMapping(value = "publish", method = RequestMethod.POST)
    public R publish(@RequestBody Map<String, Object> params) {
        return couponService.publish(params);
    }


    public void addCouponGoods(List<Integer> goods, Integer couponId) {
        for (Integer goodsId : goods) {
            CouponGoodsEntity couponGoodsEntity = new CouponGoodsEntity();
            couponGoodsEntity.setCouponId(couponId);
            couponGoodsEntity.setGoodsId(goodsId);
            couponGoodsService.save(couponGoodsEntity);
        }
    }
}
